package itsmap.systematic.exam;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.StrictMode;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Base64;
import android.widget.Toast;


public class Restapi extends Service {
	static String baseUrl = "http://130.225.184.205:8082/";	
	static String favUrl = "pfpas-mobile/rest/favorites/";	
	static String loginUrl = "http://130.225.184.205:8082/pfpas-mobile/rest/common/login";
	static String waitUrl = "pfpas-mobile/rest/mobile/suv/news/wait";
	static String newsUrl = "pfpas-mobile/rest/mobile/suv/news/news";
	static String resultsUrl = "pfpas-mobile/rest/results/";
	static String notifChunk = "/notification/mode";
	
	static String auth;
	//"c3V2OnNpa2tlcmhlZA=="
	static int code;
	
    public void onCreate() {
        super.onCreate();
        //setContentView(R.layout.startscreen);
    }
	
    private String encodeCredentials(String un, String pw) {
    	final String auth = un + ":" + pw;
        String encodedAuth = Base64.encodeToString(auth.getBytes(), Base64.DEFAULT);
        return encodedAuth.trim();    	
    }
    
	public boolean logIn() {
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);
		
		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet();
		try {
			request.setURI(new URI(this.loginUrl));
			request.setHeader("Authorization", this.auth);			
			
			HttpResponse response = client.execute(request);			
					
			if(response.getStatusLine().getStatusCode() == 200) {
				//successsuv
				return true;				
			} else {				
				// failure
				return false;
			}			
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	public boolean AddFavorite(String cpr, String note, String color) {
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);

		JSONObject jo = new JSONObject();
		try {
			jo.put("note", note);
			jo.put("color", color.toUpperCase());
		} catch (JSONException e1) {			 
			 e1.printStackTrace();
		}
	
		HttpClient client = new DefaultHttpClient();
		HttpPost request = new HttpPost();
		try {
			URI u = new URI(this.baseUrl + this.favUrl + cpr);
			request.setURI(u);
			request.setHeader("Authorization", this.auth);
			request.getParams().setParameter("CPR", cpr);

			StringEntity se = new StringEntity(jo.toString());
			
			request.setEntity(se);
			request.setHeader("Content-Type", "application/json");

			HttpResponse response = client.execute(request);
			
			this.code = response.getStatusLine().getStatusCode();
			if(this.code == 200) {
				//success
				return true;				
			} else {
				return false;
				// failure
			}	
		}catch (URISyntaxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 			
		return false;
	}
	
	private String httpcall(String url, Bundle params) throws URISyntaxException {
				
		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet();
		try {
			URI u = new URI(url);
			request.setURI(u);
			request.setHeader("Authorization", this.auth);
			
			//request.setParams("CPR", params.get("CPR").toString());
			HttpResponse response = client.execute(request);
			Header[] header = response.getAllHeaders();
			
			this.code = response.getStatusLine().getStatusCode();
			if(this.code == 200) {
				//success				
				response = client.execute(request);
				header = response.getAllHeaders();
				
				
				BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
				StringBuffer sb = new StringBuffer();
				String line = "";
				
				while((line = in.readLine()) != null) {
					sb.append(line);
				}
				return sb.toString();
				
			} else {
				return null;
				// failure
			}	
		}catch (URISyntaxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 	
		
		return null;	
	}

	private boolean removeFavorite(String cpr) {
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);

		HttpClient client = new DefaultHttpClient();
		HttpDelete request = new HttpDelete();
		try {
			URI u = new URI(this.baseUrl + this.favUrl + cpr);
			request.setURI(u);
			request.setHeader("Authorization", this.auth);
			request.getParams().setParameter("CPR", cpr);
			HttpResponse response = client.execute(request);
			
			this.code = response.getStatusLine().getStatusCode();
			if(this.code == 200) {
				//success
				return true;
			} else {
				return false;
				// failure
			}	
		}catch (URISyntaxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 	
		return false;
	}
	
	public String getFavorites() {
		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet();
		try {
			URI u = new URI(this.baseUrl + this.favUrl);
			request.setURI(u);
			request.setHeader("Authorization", this.auth);			
			HttpResponse response = client.execute(request);
			
			this.code = response.getStatusLine().getStatusCode();
			if(this.code == 200) {
				//success				
				
				BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
				StringBuffer sb = new StringBuffer();
				String line = "";
				
				while((line = in.readLine()) != null) {
					sb.append(line);
				}
				return sb.toString();
				
			} else {
				return "";
				// failure
			}	
		}catch (URISyntaxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 	
		
		return "";	
	}	
	
	static private boolean checkNews() {
		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet();
		try {
			URI u = new URI(baseUrl + waitUrl);
			request.setURI(u);
			request.setHeader("Authorization", auth);		
			
			HttpResponse response = client.execute(request);			
			code = response.getStatusLine().getStatusCode();
			if(code == 200) {
				return true;
			} else {
				return false;
				// failure
			}	
		}catch (URISyntaxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 	
		return false;
	}
	
	private String getNews() {
		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet();
		try {
			URI u = new URI(this.baseUrl + this.newsUrl);
			request.setURI(u);
			request.setHeader("Authorization", this.auth);		
			
			HttpResponse response = client.execute(request);			
			this.code = response.getStatusLine().getStatusCode();
			if(this.code == 200) {
				BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
				StringBuffer sb = new StringBuffer();
				String line = "";
				
				while((line = in.readLine()) != null) {
					sb.append(line);
				}
				return sb.toString();
			} else {
				return "";
				// failure
			}	
		}catch (URISyntaxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}			
		return "";
	}

	private String getPatientInfo(String cpr) {
		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet();
		try {
			URI u = new URI(this.baseUrl + this.resultsUrl + cpr);
			request.setURI(u);
			request.setHeader("Authorization", this.auth);		
			
			HttpResponse response = client.execute(request);
						
			this.code = response.getStatusLine().getStatusCode();
			if(this.code == 200) {				
				BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
				StringBuffer sb = new StringBuffer();
				String line = "";
				
				while((line = in.readLine()) != null) {
					sb.append(line);
				}
				return sb.toString();
				
			}	
		}catch (URISyntaxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 	
		return "";	
	}
	
	
	private void sendMessage(String type, String message) {
		Intent i = new Intent(type);
    	// You can also include some extra data.
    	i.putExtra("message", message);
    	LocalBroadcastManager.getInstance(this).sendBroadcast(i);   	
	}
	
	private void sendMessage(String type, String message, String extra, String value) {
		Intent i = new Intent(type);
    	// You can also include some extra data.
    	i.putExtra("message", message);
    	i.putExtra(extra, value);
    	LocalBroadcastManager.getInstance(this).sendBroadcast(i);   	
	}
	
	@SuppressWarnings("static-access")
	public int onStartCommand(Intent intent, int flags, int startId) {
		Integer type = intent.getIntExtra("action", -1);
        switch(type) {
        case -1:        	
        	break;
        case 1: // logIn
        	String un = intent.getStringExtra("username");
        	String pw = intent.getStringExtra("password");
        	this.auth = this.encodeCredentials(un, pw);
        	boolean val = this.logIn();        	
        	this.sendMessage("login", Boolean.toString(val));
        	break;
        case 2: // Add favorite patient
        	Intent iAddFav = intent;
        	String cpr = iAddFav.getStringExtra("cpr");
        	String note = iAddFav.getStringExtra("note");
        	String color = iAddFav.getStringExtra("color");
        	
        	boolean val1 = this.AddFavorite(cpr, note, color);
        	if(val1) {
        		this.sendMessage("AddFavorite", Boolean.toString(val1));
        	}
        	else {
        		Toast.makeText(this, "Error " + this.code, Toast.LENGTH_SHORT).show();
        		this.sendMessage("AddFavorite", Integer.toString(this.code));
        	}
        	        	
        	break;
        case 3: // Get favorites
        	String sb = this.getFavorites();
        	
        	if(sb.length() < 5) {
        		Toast.makeText(this, "Error " + this.code, Toast.LENGTH_SHORT).show();
        	}
        	
        	//intent.putExtra("favs", sb);
        	this.sendMessage("favs", sb);
        	break;
        case 4: // remove favorite
        	Intent i4 = intent;
        	String cpr4 = i4.getStringExtra("cpr");
        	boolean val4 = this.removeFavorite(cpr4);
        	if(!val4) {
        		Toast.makeText(this, "Error " + this.code, Toast.LENGTH_SHORT).show();
        	}	
        	this.sendMessage("rmFav", Integer.toString(this.code));
        	break;
        case 5: // Get patient
        	Intent i5 = intent;
        	String cpr5 = i5.getStringExtra("cpr");
        	String s5 = this.getPatientInfo(cpr5);
        	this.sendMessage("getPatientInfo", s5, "cpr", cpr5);
        	break;
        case 6: // Update patient
        	Intent i6 = intent;
        	String cpr6 = i6.getStringExtra("cpr");
        	String note6 = i6.getStringExtra("note");
        	String color6 = i6.getStringExtra("color");
        	
        	boolean val6 = this.updateFav(cpr6, note6, color6);
        	if(val6) {
        		this.sendMessage("UpdateFavorite", Boolean.toString(val6));
        	}
        	else {
        		Toast.makeText(this, "Error " + this.code, Toast.LENGTH_SHORT).show();
        		this.sendMessage("UpdateFavorite", Integer.toString(this.code));
        	}        	
        	break;
        case 7: // set mode
        	Intent i7 = intent;
        	String cpr7 = i7.getStringExtra("cpr");
        	String mode7 = i7.getStringExtra("mode");
        	boolean val7 = this.setFavMode(cpr7, mode7);
        	if(!val7) {
        		Toast.makeText(this, "Error " + this.code, Toast.LENGTH_SHORT).show();
        	}        	
        	break;
        case 90: // check for news news
        	 new Thread(new Runnable() {
        		    public void run() {
        		    	boolean val90 = Restapi.checkNews();
        	        	if(!val90 && Restapi.code != 408) {
        	        		// error
        	        	} else {        	        	
        	        		int result = (val90) ? 1 : 2;
        	        		sendMessage("checkNews", Integer.toString(result));
        	        	}
        		    }
        		  }).start();        	
        	break;
        case 91: // get news
        	String s91 = this.getNews();
        	if(s91.length() < 5) {
        		Toast.makeText(this, "Error " + this.code, Toast.LENGTH_SHORT).show();
        	}
        	
        	this.sendMessage("getNews", s91);
        	break;
        }  
		return 0;
	}
	
	private boolean updateFav(String cpr, String note, String color) {
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);

		JSONObject jo = new JSONObject();
		try {
			jo.put("note", note);
			jo.put("color", color.toUpperCase());
		} catch (JSONException e1) {			 
			 e1.printStackTrace();
		}
	
		HttpClient client = new DefaultHttpClient();
		HttpPut request = new HttpPut();
		try {
			URI u = new URI(this.baseUrl + this.favUrl + cpr);
			request.setURI(u);
			request.setHeader("Authorization", this.auth);
			request.getParams().setParameter("CPR", cpr);

			StringEntity se = new StringEntity(jo.toString());
			
			request.setEntity(se);
			request.setHeader("Content-Type", "application/json");

			HttpResponse response = client.execute(request);
			
			this.code = response.getStatusLine().getStatusCode();
			if(this.code == 200) {
				//success
				return true;				
			} else {
				return false;
				// failure
			}	
		}catch (URISyntaxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 			
		return false;
	}
	
	private boolean setFavMode(String cpr, String mode) {
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);

		JSONObject jo = new JSONObject();
		try {
			jo.put("note", mode);
		} catch (JSONException e1) {			 
			 e1.printStackTrace();
		}
	
		HttpClient client = new DefaultHttpClient();
		HttpPut request = new HttpPut();
		try {
			URI u = new URI(this.baseUrl + this.favUrl + cpr + this.notifChunk);
			request.setURI(u);
			request.setHeader("Authorization", this.auth);
			request.getParams().setParameter("CPR", cpr);

			StringEntity se = new StringEntity(jo.toString());
			
			request.setEntity(se);
			request.setHeader("Content-Type", "application/json");

			HttpResponse response = client.execute(request);
			
			this.code = response.getStatusLine().getStatusCode();
			if(this.code == 200) {
				//success
				return true;				
			} else {
				return false;
				// failure
			}	
		}catch (URISyntaxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 			
		return false;
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub	        
		return null;
	}
	
}
